package x.ovo.wechat.bot.impl.http.request.core;

import org.dromara.hutool.core.net.url.UrlBuilder;
import org.dromara.hutool.core.regex.ReUtil;
import x.ovo.wechat.bot.core.Constant;
import x.ovo.wechat.bot.core.http.request.ApiRequest;
import x.ovo.wechat.bot.core.http.result.SyncCheckResult;

import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;

public class SyncCheckRequest extends ApiRequest<SyncCheckResult> {

    public static final Pattern SYNC_CHECK_PATTERN = Pattern.compile("window.synccheck=\\{retcode:\"(\\d+)\",selector:\"(\\d+)\"}");

    @Override
    public ApiRequest<SyncCheckResult> build() {
        String s = UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.Urls.SYNCCHECK)
                .addQuery("r", System.currentTimeMillis())
                .addQuery("skey", this.session.getSKey())
                .addQuery("sid", this.session.getWxSid())
                .addQuery("uin", this.session.getWxUin())
                .addQuery("deviceid", this.session.getDeviceId())
                .addQuery("synckey", this.session.getSyncCheckKey())
                .addQuery("_", System.currentTimeMillis())
                .build();
        return this.setUrl(s);
    }

    @Override
    protected Function<String, SyncCheckResult> stringHandler() {
        return s -> {
            List<String> list = ReUtil.getAllGroups(SYNC_CHECK_PATTERN, s);
            return new SyncCheckResult(Integer.parseInt(list.get(1)), Integer.parseInt(list.get(2)));
        };
    }
}
